const TOKEN_KEY = 'Admin-Token';

const isLogin = () => {
  // return !!localStorage.getItem(TOKEN_KEY);
  return !!getCookie(TOKEN_KEY);
};

const getToken = () => {
  return getCookie(TOKEN_KEY);
};

const setToken = (token: string) => {
  setCookie(TOKEN_KEY, token);
};

const clearToken = () => {
  deleteCookie(TOKEN_KEY);
};



function setCookie(name: string, value: string) {
  const date = new Date();
  date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000));
  const expires = "expires=" + date.toUTCString();
  document.cookie = `${name}=${encodeURIComponent(value)}; ${expires}; path=/`;
}

function getCookie(name:string) {
  const cookies = document.cookie.split(';');
  for (let cookie of cookies) {
    const [cookieName, cookieValue] = cookie.trim().split('=');
    if (cookieName === name) {
      return decodeURIComponent(cookieValue);
    }
  }
  return null; // Returns null if cookie doesn't exist
}

function deleteCookie(name:string) {
  const date = new Date();
  date.setTime(date.getTime() + (-1 * 24 * 60 * 60 * 1000));
  const expires = "expires=" + date.toUTCString();
  document.cookie = `${name}=${encodeURIComponent("")}; ${expires}; path=/`;
}

export { isLogin, getToken, setToken, clearToken };
